package com.android.waterdetection;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.android.waterdetection.bean.UserBean;
import com.android.waterdetection.dao.DBService;
import com.android.waterdetection.event.LoginDataEvent;
import com.android.waterdetection.event.RegisterDataEvent;
import com.android.waterdetection.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    private EditText mEdtName;
    private EditText mEdtPass;
    private Button mBtnLogin;
    private Button mBtnLogout;
    private List<UserBean> mUserBeans;
    private ProgressBar mProgressBar;
    private CheckBox mCheckBoxAutoL;
    private ImageView mImgPassSh;
    private TextView mTvAdmin;

    private SharedPreferences.Editor mAutoLoginShareEdit;
    private SharedPreferences.Editor mLoginNameShareEdit;
    private SharedPreferences.Editor mPassWordShareEdit;
    private SharedPreferences mAutoLoginSharedPreferences;
    private SharedPreferences mLoginNameSharedPreferences;
    private SharedPreferences mPassWordSharedPreferences;

    private boolean isShowPassword = false;
    private boolean mIsLogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        EventBus.getDefault().register(this);
        this.getSupportActionBar().hide();

        initView();
        initData();
        initListener();
    }

    private void initListener() {
        mBtnLogin.setOnClickListener(view -> {
            String name = mEdtName.getText().toString().trim();
            String pass = mEdtPass.getText().toString().trim();
            if (name.length() <= 0) {
                ToastUtil.showToast(this, getString(R.string.login_fail));
                return;
            }
            mProgressBar.setVisibility(View.VISIBLE);
            new Thread(() -> {
                mUserBeans = DBService.queryUser();

                Log.d(TAG, "setOnClickListener-mUserBeans->" + mUserBeans);
                if (mUserBeans != null) {
                    EventBus.getDefault().post(new LoginDataEvent(name, pass, true));
                } else {
                    EventBus.getDefault().post(new LoginDataEvent(name, pass, false));
                }
            }).start();
        });

        mBtnLogout.setOnClickListener(view -> {
            String name = mEdtName.getText().toString().trim();
            String pass = mEdtPass.getText().toString().trim();
            //注册
            if (name.isEmpty() || pass.isEmpty()) {
                ToastUtil.showToast(this, getString(R.string.logout_fail_not_null));
            } else {
                mProgressBar.setVisibility(View.VISIBLE);

                new Thread(() -> {
                    boolean isInsert = DBService.insertUser(name, pass);

                    EventBus.getDefault().post(new RegisterDataEvent(isInsert));
                }).start();
            }
        });
        mImgPassSh.setOnClickListener(v -> {
            isShowPassword = !isShowPassword;
            if (isShowPassword) {
                mImgPassSh.setImageResource(R.drawable.pass_hide);
                mEdtPass.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            } else {
                mImgPassSh.setImageResource(R.drawable.pass_show);
                mEdtPass.setTransformationMethod(PasswordTransformationMethod.getInstance());
            }
        });
        //管理员登录
        mTvAdmin.setOnClickListener(v -> {
            String name = mEdtName.getText().toString().trim();
            String pass = mEdtPass.getText().toString().trim();
            if (name.equals("admin") && pass.equals("admin")) {
                ToastUtil.showToast(this,"管理员登录成功");
                startActivity(new Intent(this,AdminActivity.class));
            } else {
                ToastUtil.showToast(this,"管理员登录失败,请检查账号和密码");
            }
        });
    }

    private void initData() {
        mAutoLoginSharedPreferences = getSharedPreferences("autoLogin", MODE_PRIVATE);
        mLoginNameSharedPreferences = getSharedPreferences("loginName", MODE_PRIVATE);
        mPassWordSharedPreferences = getSharedPreferences("password", MODE_PRIVATE);
        boolean autoLogin = mAutoLoginSharedPreferences.getBoolean("autoLogin", false);
        String loginName = mLoginNameSharedPreferences.getString("loginName", null);
        String password = mPassWordSharedPreferences.getString("password", null);
        mAutoLoginShareEdit = mAutoLoginSharedPreferences.edit();
        mLoginNameShareEdit = mLoginNameSharedPreferences.edit();
        mPassWordShareEdit = mPassWordSharedPreferences.edit();
        if (autoLogin) {
            Intent intent = new Intent(this, HomeActivity.class);
            intent.putExtra("loginName", loginName);
            intent.putExtra("password", password);
            startActivity(intent);
        }
    }

    private void initView() {
        mEdtName = findViewById(R.id.edt_name);
        mEdtPass = findViewById(R.id.edt_pass);
        mBtnLogin = findViewById(R.id.btn_login);
        mBtnLogout = findViewById(R.id.btn_logout);
        mProgressBar = findViewById(R.id.pro_loading);
        mCheckBoxAutoL = findViewById(R.id.check_auto_login);
        mImgPassSh = findViewById(R.id.img_pass_sh);
        mTvAdmin = findViewById(R.id.tv_admin);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getLoginDataSuccess(LoginDataEvent event) {
        String name = event.getUsername();
        String pass = event.getPassword();
        boolean loginStatus1 = event.isLoginStatus();
        if (loginStatus1) {
            String loginName = "";
            String password = "";
            for (int i = 0; i < mUserBeans.size(); i++) {
                UserBean userBean = mUserBeans.get(i);
                mIsLogin = userBean.getUsername().equals(name) && userBean.getPassword().equals(pass);
                if (mIsLogin) {
                    loginName = name;
                    password = pass;
                    break;
                }
            }
            if (mIsLogin) {
                //登录
                mProgressBar.setVisibility(View.GONE);
                ToastUtil.showToast(this, getString(R.string.login_success));
                boolean checked = mCheckBoxAutoL.isChecked();
                mAutoLoginShareEdit.putBoolean("autoLogin", checked);
                mLoginNameShareEdit.putString("loginName", loginName);
                mPassWordShareEdit.putString("password", password);
                mAutoLoginShareEdit.apply();
                mLoginNameShareEdit.apply();
                mPassWordShareEdit.apply();
                Intent intent = new Intent(this, HomeActivity.class);
                intent.putExtra("loginName", loginName);
                intent.putExtra("password", password);
                this.startActivity(intent);
            } else {
                mProgressBar.setVisibility(View.GONE);
                ToastUtil.showToast(this, getString(R.string.login_fail));
            }
        } else {
            mProgressBar.setVisibility(View.GONE);
            ToastUtil.showToast(this, getString(R.string.login_fail));
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getRegisterStatus(RegisterDataEvent event) {
        mProgressBar.setVisibility(View.GONE);

        boolean registerStatus = event.isRegisterStatus();
        if (registerStatus) {
            ToastUtil.showToast(this, getString(R.string.logout_success));
        } else {
            ToastUtil.showToast(this, getString(R.string.logout_fail_dao));
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}